<script setup lang="ts">
import { ref, reactive, onMounted, h } from 'vue';
import { NButton, NSpace, NTag, NDrawer, NDescriptions, NDescriptionsItem, NCard, NStatistic, NGrid, NGridItem } from 'naive-ui';
import { fetchCollectionErrors, fetchCollectionErrorDetail, fetchErrorStatistics } from '@/service/api';
import { useLoading } from '@sa/hooks';
import * as echarts from 'echarts';

defineOptions({
  name: 'FileCollectionError'
});

const { loading, startLoading, endLoading } = useLoading(false);
const { loading: detailLoading, startLoading: startDetailLoading, endLoading: endDetailLoading } = useLoading(false);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  taskId: undefined as number | undefined,
  fileId: undefined as number | undefined,
  errorType: '',
  startTime: null as string | null,
  endTime: null as string | null
});

// 表格数据
const tableData = ref<any[]>([]);
const total = ref(0);

// 统计数据
const statistics = ref<Record<string, any>>({});

// 详情抽屉
const detailDrawerVisible = ref(false);
const currentError = ref<any>(null);

// 图表容器
const chartRef = ref<HTMLElement | null>(null);
let chartInstance: echarts.ECharts | null = null;

// 错误类型选项
const errorTypeOptions = [
  { label: '全部', value: '' },
  { label: '文件获取错误', value: 'FILE_FETCH_ERROR' },
  { label: '文件解析错误', value: 'FILE_PARSE_ERROR' },
  { label: '数据校验错误', value: 'DATA_VALIDATION_ERROR' },
  { label: '数据加载错误', value: 'DATA_LOAD_ERROR' },
  { label: '系统错误', value: 'SYSTEM_ERROR' }
];

// 表格列定义
const columns = [
  {
    title: '错误类型',
    key: 'errorType',
    width: 150,
    render: (row: any) => {
      return h(NTag, { type: 'error' }, { default: () => row.errorType });
    }
  },
  {
    title: '文件名',
    key: 'fileName',
    width: 200,
    ellipsis: { tooltip: true }
  },
  {
    title: '记录索引',
    key: 'recordIndex',
    width: 100,
    align: 'right'
  },
  {
    title: '错误信息',
    key: 'errorMessage',
    width: 300,
    ellipsis: { tooltip: true }
  },
  {
    title: '发生时间',
    key: 'createTime',
    width: 180
  },
  {
    title: '操作',
    key: 'actions',
    width: 100,
    fixed: 'right',
    render: (row: any) => {
      return h(
        NButton,
        {
          size: 'small',
          onClick: () => handleViewDetail(row.id)
        },
        { default: () => '详情' }
      );
    }
  }
];

// 查询列表
async function getList() {
  startLoading();
  try {
    const { data } = await fetchCollectionErrors(queryParams);
    if (data) {
      tableData.value = data.rows || [];
      total.value = data.total || 0;
    }
  } finally {
    endLoading();
  }
}

// 查询统计
async function getStatistics() {
  try {
    const { data } = await fetchErrorStatistics(queryParams);
    if (data) {
      statistics.value = data;
      renderChart();
    }
  } catch (error) {
    console.error('获取统计数据失败:', error);
  }
}

// 渲染图表
function renderChart() {
  if (!chartRef.value) return;

  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value);
  }

  const errorTypeStats = statistics.value.errorTypeStats || {};
  const data = Object.entries(errorTypeStats).map(([name, value]) => ({
    name,
    value
  }));

  const option = {
    title: {
      text: '错误类型分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '错误类型',
        type: 'pie',
        radius: '50%',
        data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  };

  chartInstance.setOption(option);
}

// 搜索
function handleSearch() {
  queryParams.pageNum = 1;
  getList();
  getStatistics();
}

// 重置
function handleReset() {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    taskId: undefined,
    fileId: undefined,
    errorType: '',
    startTime: null,
    endTime: null
  });
  getList();
  getStatistics();
}

// 查看详情
async function handleViewDetail(id: number) {
  startDetailLoading();
  try {
    const { data } = await fetchCollectionErrorDetail(id);
    if (data) {
      currentError.value = data;
      detailDrawerVisible.value = true;
    }
  } finally {
    endDetailLoading();
  }
}

// 分页变化
function handlePageChange(page: number) {
  queryParams.pageNum = page;
  getList();
}

function handlePageSizeChange(pageSize: number) {
  queryParams.pageSize = pageSize;
  queryParams.pageNum = 1;
  getList();
}

onMounted(() => {
  getList();
  getStatistics();
});
</script>

<template>
  <div class="h-full flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <!-- 统计卡片 -->
    <NCard title="错误统计" :bordered="false" class="card-wrapper">
      <NGrid :cols="4" :x-gap="16">
        <NGridItem>
          <NStatistic label="总错误数" :value="statistics.totalErrors || 0" />
        </NGridItem>
        <NGridItem>
          <NStatistic label="错误文件数" :value="statistics.fileErrorCount || 0" />
        </NGridItem>
        <NGridItem>
          <NStatistic label="错误任务数" :value="statistics.taskErrorCount || 0" />
        </NGridItem>
        <NGridItem>
          <div ref="chartRef" style="width: 100%; height: 200px"></div>
        </NGridItem>
      </NGrid>
    </NCard>

    <!-- 查询表单 -->
    <NCard title="查询条件" :bordered="false" class="card-wrapper">
      <NSpace vertical>
        <NSpace>
          <NInputNumber
            v-model:value="queryParams.taskId"
            placeholder="任务ID"
            clearable
            style="width: 150px"
          />
          <NInputNumber
            v-model:value="queryParams.fileId"
            placeholder="文件ID"
            clearable
            style="width: 150px"
          />
          <NSelect
            v-model:value="queryParams.errorType"
            :options="errorTypeOptions"
            placeholder="错误类型"
            clearable
            style="width: 200px"
          />
          <NDatePicker
            v-model:value="queryParams.startTime"
            type="datetime"
            placeholder="开始时间"
            clearable
            style="width: 200px"
          />
          <NDatePicker
            v-model:value="queryParams.endTime"
            type="datetime"
            placeholder="结束时间"
            clearable
            style="width: 200px"
          />
        </NSpace>
        <NSpace>
          <NButton type="primary" @click="handleSearch">
            <template #icon>
              <icon-ic-round-search />
            </template>
            搜索
          </NButton>
          <NButton @click="handleReset">
            <template #icon>
              <icon-ic-round-refresh />
            </template>
            重置
          </NButton>
        </NSpace>
      </NSpace>
    </NCard>

    <!-- 数据表格 -->
    <NCard title="错误记录" :bordered="false" class="card-wrapper flex-1-hidden">
      <NDataTable
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :scroll-x="1000"
        :pagination="{
          page: queryParams.pageNum,
          pageSize: queryParams.pageSize,
          itemCount: total,
          showSizePicker: true,
          pageSizes: [10, 20, 50, 100],
          onUpdatePage: handlePageChange,
          onUpdatePageSize: handlePageSizeChange
        }"
        flex-height
        class="flex-1-hidden"
      />
    </NCard>

    <!-- 详情抽屉 -->
    <NDrawer v-model:show="detailDrawerVisible" :width="600" title="错误记录详情">
      <NCard v-if="currentError" :bordered="false">
        <NDescriptions :column="1" label-placement="left">
          <NDescriptionsItem label="错误类型">
            <NTag type="error">{{ currentError.errorType }}</NTag>
          </NDescriptionsItem>
          <NDescriptionsItem label="文件名">{{ currentError.fileName }}</NDescriptionsItem>
          <NDescriptionsItem label="任务ID">{{ currentError.taskId }}</NDescriptionsItem>
          <NDescriptionsItem label="文件ID">{{ currentError.fileId }}</NDescriptionsItem>
          <NDescriptionsItem label="记录索引">{{ currentError.recordIndex }}</NDescriptionsItem>
          <NDescriptionsItem label="错误信息">
            <span class="text-red">{{ currentError.errorMessage }}</span>
          </NDescriptionsItem>
          <NDescriptionsItem label="记录数据">
            <pre class="text-xs">{{ currentError.recordData }}</pre>
          </NDescriptionsItem>
          <NDescriptionsItem label="发生时间">{{ currentError.createTime }}</NDescriptionsItem>
        </NDescriptions>
      </NCard>
    </NDrawer>
  </div>
</template>

<style scoped>
.card-wrapper {
  box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
}

pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  background-color: #f5f5f5;
  padding: 8px;
  border-radius: 4px;
}
</style>
